﻿using System;
using System.IO;

namespace OpenLS.Spreadsheet.Formats.Biff.Records
{
    internal class ContinueFrt12Record : BiffRecord
    {
        private byte[] _buffer;
        private FrtRefHeader frtRefHeader = new FrtRefHeader(){grbitFrt = FrtFlags.fFrtAlert};

        public ContinueFrt12Record(Action<BinaryWriter> bufferAction, RangeAddress address)
        {
            frtRefHeader.rt = 0x87f;
            frtRefHeader.ref8 = (Ref8) address;
            using (MemoryStream memoryStream = new MemoryStream())
            {
                using (BinaryWriter writer = new BinaryWriter(memoryStream))
                {
                    bufferAction(writer);
                    writer.Flush();
                    memoryStream.Position = 0;
                    _buffer = new byte[memoryStream.Length];
                    memoryStream.Read(_buffer, 0, _buffer.Length);
                }
            }
        }

        public ContinueFrt12Record()
        {
        }

        protected override void ReadContent(BiffReaderContext context, int length)
        {
            frtRefHeader = new FrtRefHeader();
            frtRefHeader.Read(context.Reader);
            this._buffer = context.ReadBytes(length - FrtRefHeader.Size);
        }

        internal override BiffRecordType RecordType
        {
            get { return BiffRecordType.ContinueFrt12; }
        }

        internal override void WriteContent(BiffWriterWorkbookContext context)
        {
            this.frtRefHeader.Write(context.Writer);
            context.Write(_buffer);
        }

        public T GetItem<T>(OpenLS.Spreadsheet.Func<BinaryReader, T> p0)
        {
            using (MemoryStream stream = new MemoryStream(_buffer))
            {
                using (BinaryReader reader = new BinaryReader(stream))
                {
                    return p0(reader);
                }
            }
        }
    }
}